package net.hn.hnms.biz.plan.service.impl;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.util.StrUtil;
import com.baomidou.dynamic.datasource.annotation.DS;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import net.hn.hnms.biz.plan.domain.ExecutionCost;
import net.hn.hnms.biz.plan.mapper.ExecutionCostMapper;
import net.hn.hnms.biz.plan.request.ExecutionCostReq;
import net.hn.hnms.biz.plan.service.IExecutionCostService;
import net.hn.hnms.biz.plan.vo.ExecutionCostVO;
import net.hn.hnms.sys.common.core.constant.Constants;
import net.hn.hnms.sys.common.core.domain.ResponsePage;
import net.hn.hnms.sys.common.core.exception.HuaNengException;
import net.hn.hnms.sys.common.mybatis.core.page.PageQuery;
import net.hn.hnms.sys.system.api.RemoteUserService;
import net.hn.hnms.sys.system.api.model.LoginUser;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.List;
import java.util.Optional;
import java.util.stream.Collectors;

/**
 * @author zhaoyang
 * 生产成本计划执行管理服务层实现
 * @date 2022-08-01
 */

@Service
@DS("master")
public class ExecutionCostServiceImpl extends BaseService<ExecutionCost, ExecutionCostVO> implements IExecutionCostService {

    @Autowired
    private ExecutionCostMapper executionCostMapper;
    @Autowired
    private RemoteUserService remoteUserService;
    /**
     * @param executionCost
     * @param pageQuery       查询生产成本计划执行列表
     */
    @Override
    public ResponsePage<ExecutionCostVO> selectPageList(ExecutionCostReq executionCost, PageQuery pageQuery) {

        Page<ExecutionCost> page = executionCostMapper.selectPage(pageQuery.build(), buildQuery(executionCost).orderByDesc(ExecutionCost::getExecutionDate).orderByDesc(ExecutionCost::getCreateTime));
        List<ExecutionCostVO> list =page.getRecords().stream().map(o ->convert(o, ExecutionCostVO.class)).collect(Collectors.toList());
        list.forEach(ii->{
            LoginUser userInfoById = remoteUserService.getUserInfoById(Long.valueOf(ii.getCreateUserId()));
            if (Optional.ofNullable(userInfoById).isPresent()) {
                ii.setCreateUserName(userInfoById.getNickname());
            }

        });
        return new ResponsePage<>(list, page.getTotal());
    }

    /**
     * 构造查询条件
     * @param req
     * @return LambdaQueryWrapper<ExecutionCost> 查询条件
     */
    private LambdaQueryWrapper<ExecutionCost> buildQuery(ExecutionCostReq req){
        return new LambdaQueryWrapper<ExecutionCost>()
//                .eq(StrUtil.isNotBlank(req.getMineCode()), ExecutionCost::getMineCode, req.getMineCode())
                .ge(req.getBeginDate() != null, ExecutionCost::getExecutionDate, req.getBeginDate())
                .le(req.getEndDate() != null, ExecutionCost::getExecutionDate, req.getEndDate())
                .and(o->o.eq(req.getMineCode()!=null, ExecutionCost::getMineCode, req.getMineCode()).or().eq(req.getCompanyCode()!=null, ExecutionCost::getCompanyCode, req.getCompanyCode()));

    }

    /**
     *
     * @param executionCost
     * 查询带值班人员列表
     */
    @Override
    public List<ExecutionCostVO> selectList(ExecutionCostReq executionCost) {
        List<ExecutionCost> list = executionCostMapper.selectList(buildQuery(executionCost));
        return list.stream().map(o -> convert(o, ExecutionCostVO.class)).collect(Collectors.toList());
    }

    /**
     * @param executionCost 新增生产成本计划执行
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public int insert(ExecutionCostReq executionCost) {
//        QueryWrapper<ExecutionCost> queryWrapper = new QueryWrapper<>();
//        queryWrapper.eq("development_plan_code", executionCost.getExecutionCostCode());
//        if (executionCostMapper.selectCount(queryWrapper) > 0) {
//            throw new HuaNengException(Constants.FAIL, "已存在同一时段的计划");
//        }
        ExecutionCost insertObj = new ExecutionCost();
        BeanUtil.copyProperties(executionCost, insertObj);
        return executionCostMapper.insert(insertObj);
    }

    /**
     * @param idList 批量删除 id集合
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public void deleteBatch(List<String> idList) {
        executionCostMapper.deleteBatchIds(idList);
    }

    /**
     * @param executionCost 单个修改 按照主键修改信息
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public void updateById(ExecutionCostReq executionCost) {
        if (StrUtil.isBlank(executionCost.getCostExecutionId())) {
            throw new HuaNengException(Constants.FAIL, "id不能为空");
        }
        ExecutionCost updateObj = new ExecutionCost();
        BeanUtil.copyProperties(executionCost, updateObj);
        int updateCount = executionCostMapper.updateById(updateObj);
        if (updateCount == 0) {
            throw new HuaNengException(Constants.FAIL, "数据不存在");
        }
    }

    /**
     * @param id 按主键id查询详情
     */
    @Override
    public ExecutionCostVO selectDetailById(String id) {
        ExecutionCost executionCost = executionCostMapper.selectById(id);
        if (executionCost == null) {
            throw new HuaNengException(Constants.FAIL, "数据不存在");
        }
        return convertWithUser(executionCost, ExecutionCostVO.class);
    }
}
